package yannan.voiplock4ble.service.ble;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockBeanDao;
import yannan.voiplock4ble.bean.LockKeyBean;
import yannan.voiplock4ble.bean.LockKeyBeanDao;
import yannan.voiplock4ble.bean.LockKeyTemp;
import yannan.voiplock4ble.bean.LockKeyTempDao;
import yannan.voiplock4ble.bean.LockRecordBean;
import yannan.voiplock4ble.bean.ble.AddPwd;
import yannan.voiplock4ble.bean.ble.AddVein;
import yannan.voiplock4ble.bean.ble.BleResponseFactory;
import yannan.voiplock4ble.bean.ble.ConnectLock;
import yannan.voiplock4ble.bean.ble.DelKey;
import yannan.voiplock4ble.bean.ble.LockInfo;
import yannan.voiplock4ble.bean.ble.LockTime;
import yannan.voiplock4ble.bean.ble.LockUpgradeComplete;
import yannan.voiplock4ble.bean.ble.OperAdmin;
import yannan.voiplock4ble.bean.ble.OperKey;
import yannan.voiplock4ble.bean.ble.PwdUser;
import yannan.voiplock4ble.bean.ble.RemoteUpgradeACK;
import yannan.voiplock4ble.bean.ble.SetLockTime;
import yannan.voiplock4ble.bean.ble.UnLockRecord;
import yannan.voiplock4ble.bean.ble.UpdatePktACK;
import yannan.voiplock4ble.bean.ble.VeinKey;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.LockBeanDaoManager;
import yannan.voiplock4ble.db.daomanager.LockKeyDaoManager;
import yannan.voiplock4ble.db.daomanager.LockKeyTempDaoManager;
import yannan.voiplock4ble.db.daomanager.LockRecordDaoManager;
import yannan.voiplock4ble.eventbus.AddPwdMsg;
import yannan.voiplock4ble.eventbus.AddVeinMsg;
import yannan.voiplock4ble.eventbus.ConnectFailedMsg;
import yannan.voiplock4ble.eventbus.DelPwdMsg;
import yannan.voiplock4ble.eventbus.DelVeinMsg;
import yannan.voiplock4ble.eventbus.EventObject;
import yannan.voiplock4ble.eventbus.LockTimeMsg;
import yannan.voiplock4ble.eventbus.OperAdminMsg;
import yannan.voiplock4ble.eventbus.OperPwdMsg;
import yannan.voiplock4ble.eventbus.OperVeinMsg;
import yannan.voiplock4ble.eventbus.PwdListMsg;
import yannan.voiplock4ble.eventbus.RemoteUpgradeACKMsg;
import yannan.voiplock4ble.eventbus.SearchLockBleMsg;
import yannan.voiplock4ble.eventbus.SetLockTimeMsg;
import yannan.voiplock4ble.eventbus.UnlockRecordMsg;
import yannan.voiplock4ble.eventbus.UpgradeACKMsg;
import yannan.voiplock4ble.eventbus.VeinKeyListMsg;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.task.UpLoadLockInfoTask;
import yannan.voiplock4ble.utils.LogUtils;
import yannan.voiplock4ble.utils.TimeUtils;

/**
 * 说明：处理门锁返回报文的工具类
 * 作者：mainTel
 * 时间：2016/12/4 17:01
 * 备注：
 */
public class BleResponeUtils {

    /**
     * 处理返回报文
     *
     * @param response 具体报文
     */
    public static void handle(byte[] response) {
        //数组的下标为6的是标志是什么接口的标志位
        int order = response[6] & 0XFF;
        switch (order) {
            case BleUtils.ORDER_CONNECT_LOCK: //门锁链接
                ConnectLock contentLock = (ConnectLock) BleResponseFactory.create(response);
                if (MyApplication.getInterface().mConnectLock != null) {
                    MyApplication.getInterface().mConnectLock.contentToken = contentLock.contentToken;
                    MyApplication.getInterface().mConnectLock.operResult = contentLock.operResult;
                    MyApplication.getInterface().mConnectLock.phoneMatchType = contentLock.phoneMatchType;
                    MyApplication.getInterface().mConnectLock.protoVersion = contentLock.protoVersion;
                    MyApplication.getInterface().mConnectLock.firmwareVersion = contentLock.firmwareVersion;
                } else {
                    MyApplication.getInterface().mConnectLock = contentLock;
                }
                if (contentLock != null) {
                    EventBus.getDefault().post(new SearchLockBleMsg(contentLock.phoneMatchType));
                    EventBus.getDefault().post(new ConnectFailedMsg(true));
                }
                break;
            case BleUtils.ORDER_GET_LOCK_INFO:
                LockInfo lockInfo = (LockInfo) BleResponseFactory.create(response);
                if (lockInfo != null)
                    saveLockInfo(lockInfo);
                break;
            case BleUtils.APP_REGISTER_PWD_ID:
                AddPwd addPwd = (AddPwd) BleResponseFactory.create(response);
                if (addPwd != null)
                    EventBus.getDefault().post(new AddPwdMsg(addPwd));
                break;
            case BleUtils.APP_GET_PW_LIST_ID://获取密码列表
                PwdUser pwdUser = (PwdUser) BleResponseFactory.create(response);
                if (pwdUser.getTotalPwd() > 0)
                    savePwdUser(pwdUser);
                else
                    EventBus.getDefault().post(new PwdListMsg(true));
                break;
            case BleUtils.APP_GET_LOCK_TIME_ID:
                LockTime lockTime = (LockTime) BleResponseFactory.create(response);
                if (lockTime != null)
                    EventBus.getDefault().post(new LockTimeMsg(lockTime.time));
                break;
            case BleUtils.APP_SET_LOCK_TIME_ID:
                SetLockTime setLockTime = (SetLockTime) BleResponseFactory.create(response);
                if (setLockTime != null)
                    EventBus.getDefault().post(new SetLockTimeMsg(setLockTime.isSuccess));
                break;
            case BleUtils.APP_GET_UNLOCK_RECORD_ID://开锁记录
                UnLockRecord unLockRecord = (UnLockRecord) BleResponseFactory.create(response);
                if (unLockRecord != null) {
                    EventBus.getDefault().post(new UnlockRecordMsg(1));
                    saveUnlockRecord(unLockRecord);
                }
                break;
            case BleUtils.APP_REGISTER_FINGER_ID:
                AddVein addVein = (AddVein) BleResponseFactory.create(response);
                if (addVein != null) {
                    EventBus.getDefault().post(new AddVeinMsg(addVein));
                }
                break;
            case BleUtils.APP_GET_FINGER_LIST_ID: //全部指静脉列表
                //全部删除应该发送一个长度是14的response
                if (response.length == 14) {
                    //发送需要删除的消息
                    EventBus.getDefault().post(new VeinKeyListMsg(true));
                } else {
                    VeinKey veinKey = (VeinKey) BleResponseFactory.create(response);
                    if (veinKey != null) {
                        saveVeinUser(veinKey);
                    }
                }
                break;
            case BleUtils.APP_DELETE_FINGER_ID:
                DelKey delVein = (DelKey) BleResponseFactory.create(response);
                if (delVein != null) {
                    EventBus.getDefault().post(new DelVeinMsg(delVein));
                }
                break;
            case BleUtils.APP_DELETE_PWD_ID:
                DelKey delPwd = (DelKey) BleResponseFactory.create(response);
                if (delPwd != null) {
                    EventBus.getDefault().post(new DelPwdMsg(delPwd));
                }
                break;
            case BleUtils.APP_OPEN_AND_CLOSE_PWD_ID:
                OperKey operPwd = (OperKey) BleResponseFactory.create(response);
                if (operPwd != null) {
                    EventBus.getDefault().post(new OperPwdMsg(operPwd.isSuc));
                }
                break;
            case BleUtils.APP_OPEN_AND_CLOSE_FINGER_ID:
                OperKey operVein = (OperKey) BleResponseFactory.create(response);
                if (operVein != null) {
                    EventBus.getDefault().post(new OperVeinMsg(operVein.isSuc));
                }
                break;
            case BleUtils.APP_ADMIN_AUTHORITY_OPER_ID:
                OperAdmin operAdmin = (OperAdmin) BleResponseFactory.create(response);
                if (operAdmin != null) {
                    EventBus.getDefault().post(new OperAdminMsg(operAdmin.resultType));
                }
                break;
            case BleUtils.Remote_Upgrade_ACK_ID:
                RemoteUpgradeACK remoteUpgradeACK = (RemoteUpgradeACK) BleResponseFactory.create(response);
                if (remoteUpgradeACK != null) { //发送消息给 LockUpdateActivity
                    EventBus.getDefault().post(new RemoteUpgradeACKMsg(remoteUpgradeACK));
                }
                break;
            case BleUtils.APP_Send_Upgrade_Pkt_ACK_ID: //发送升级包
                UpdatePktACK updatePktACK = (UpdatePktACK) BleResponseFactory.create(response);
                if (updatePktACK != null) {
                    EventBus.getDefault().post(new UpgradeACKMsg(updatePktACK));
                }
                break;
            case BleUtils.APP_Upgrade_complete_ACK_ID:
                LockUpgradeComplete upgradeComplete = (LockUpgradeComplete) BleResponseFactory.create(response);
                if (upgradeComplete != null) {
                    EventBus.getDefault().post(new EventObject(upgradeComplete.reason));
                }
                break;
        }
    }

    /**
     * 存储开锁记录
     *
     * @param unLockRecord
     */
    private static void saveUnlockRecord(UnLockRecord unLockRecord) {
        /*
        public String unlockingDate;
        public String nickName;
        public String unlockinType;  //开锁方式 0 指静脉 1 密码
        public String userIdentifier;
        public String lockserialId; //锁序列号
         */
        LockRecordBean lockRecordBean = new LockRecordBean();
        lockRecordBean.unlockingDate = TimeUtils.getDateToString2(unLockRecord.timeStamp * 1000);
        lockRecordBean.userIdentifier = unLockRecord.userNumber;
        lockRecordBean.unlockinType = unLockRecord.unlockType == 2 ? "1" : "0";
        lockRecordBean.lockserialId = MyApplication.getInterface().mConnectLock.lockserialId;
        DaoUtils.getDao(LockRecordDaoManager.class).insert(lockRecordBean);
    }

    /**
     * 存储指静脉用户
     *
     * @param veinKey
     */
    private static void saveVeinUser(VeinKey veinKey) {

            /*
             * userIdentifier	手机号1
             * nickName	别名1
             * userPermission	是否是管理员（0不是 1是）[1
             * isBan	是否被禁止开门（1:启用；0:未启用）1
             * type	用户类型（0:指静脉；1:密码）[1
             * lockserialId	锁的序列号[1
             * registerTime	注册时间1
             * userId	用户id（没有注册app帐号时为null）1
             */
        try {
            List<LockKeyTemp> list = DaoUtils.getDao(LockKeyTempDaoManager.class).getQueryBuilder()
                    .where(LockKeyTempDao.Properties.LockserialId.eq(MyApplication.getInterface().mConnectLock.lockserialId),
                            LockKeyTempDao.Properties.UserIdentifier.eq(veinKey.phoneNum))
                    .build().list();
            LockKeyBean keyBean = new LockKeyBean();
            if (list.size() != 0) {
                LockKeyTemp lockKeyTemp = list.get(0);
                keyBean.nickName = lockKeyTemp.nickName;
                keyBean.userId = lockKeyTemp.userId;
            }
            keyBean.type = "0";
            keyBean.userIdentifier = veinKey.phoneNum;
            keyBean.userPermission = (veinKey.fingerUserType == 1 ? 0 : 1) + "";
            keyBean.lockserialId = MyApplication.getInterface().mConnectLock.lockserialId;
            keyBean.templateGroupId = veinKey.templateGroupId + "";
            keyBean.templateId = veinKey.templateId + "";
            keyBean.isBan = veinKey.fingerEnableFlag + "";
            long time = ((long) veinKey.timeStamp) * 1000;
            keyBean.registerTime = TimeUtils.getDateToString2(time);
            EventBus.getDefault().post(new VeinKeyListMsg(keyBean));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储密码用户
     *
     * @param pwdUser
     */
    private static void savePwdUser(PwdUser pwdUser) {
        for (PwdUser.PwdUserItem item : pwdUser.pwdUserItems) {
            /*
             * userIdentifier	手机号
             * nickName	别名
             * userPermission	是否是管理员（0不是 1是）[
             * isBan	是否被禁止开门（1:启用；0:未启用）
             * type	用户类型（0:指静脉；1:密码）[
             * lockserialId	锁的序列号[
             * registerTime	注册时间
             * userId	用户id（没有注册app帐号时为null）[
             */
            try {
                List<LockKeyTemp> list = DaoUtils.getDao(LockKeyTempDaoManager.class).getQueryBuilder()
                        .where(LockKeyTempDao.Properties.LockserialId.eq(MyApplication.getInterface().mConnectLock.lockserialId),
                                LockKeyTempDao.Properties.UserIdentifier.eq(item.userId))
                        .build().list();
                LockKeyBean keyBean = new LockKeyBean();
                if (list.size() != 0) {
                    LockKeyTemp lockKeyTemp = list.get(0);
                    keyBean.nickName = lockKeyTemp.nickName;
                    keyBean.userId = lockKeyTemp.userId;
                }
                keyBean.type = "1";
                keyBean.userPermission = "0";
                keyBean.lockserialId = MyApplication.getInterface().mConnectLock.lockserialId;
                keyBean.userIdentifier = item.userId + "";
                keyBean.isBan = item.pwdEnableFlag + "";
                keyBean.registerTime = TimeUtils.getDateToString2(item.timeStamp * 1000);
                EventBus.getDefault().post(new PwdListMsg(keyBean));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 存储门锁信息
     *
     * @param lockInfo
     */
    private static void saveLockInfo(LockInfo lockInfo) {
        try {
            LockBean lockBean = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder()
                    .where(LockBeanDao.Properties.LockserialId.eq(MyApplication.getInterface().mConnectLock.lockserialId))
                    .build().list().get(0);
            lockBean.batteryQuantity = lockInfo.dumpEnergy;
            lockBean.veinKeyState = lockInfo.allFingerEnable;
            lockBean.pwdKeyState = lockInfo.allPwdEnable;
            DaoUtils.getDao(LockBeanDaoManager.class).insertOrReplace(lockBean);
            UpLoadLockInfoTask.create(lockBean).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
